<?php
namespace app\common\model\factory;

use think\Model;
use app\common\model\factory\Factory;

class User extends Model
{
    protected $table = 'user';
    protected $pk = 'UserId';
    const STATEOK = 1; 
    // 关联工厂
    public function factories()
    {
        return $this->belongsToMany(
            Factory::class,
            'user_factory',
            'factory_id',
            'user_id'
        );
    }

    // 更新用户信息
    public static function updateInfo($userId, $data)
    {
        $user = self::find($userId);
        if (!$user) {
            return false;
        }
        $user->Name = $data['Name'];
        $user->Iphone = $data['Iphone'];
        $user->Sex = $data['sex'];
        return $user->save();
    }

    // 删除用户及关联
    public static function deleteUser($userId)
    {
        $user = self::find($userId);
        if (!$user) {
            return false;
        }

        self::startTrans();
        try {
            // 删除用户与工厂的关联
            db('user_factory')->where('user_id', $userId)->delete();
            // 删除用户
            $user->delete();
            self::commit();
            return true;
        } catch (\Exception $e) {
            self::rollback();
            return false;
        }
    }

    // 获取用户绑定的工厂ID
    public static function getFactoryId($userId)
    {
        return db('user_factory')
            ->where('user_id', $userId)
            ->value('factory_id');
    }
}